import { useState, useEffect, useRef } from "react";
import { CommonModal } from "@/views/components/CommonModal";
import { CommonField } from "@/pages/OrderModule/common/components/CommonForm";
// import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
// import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { PrefixPlaceholder, Input, PreInputNumber, CommonInput, CommonInputNumber } from "@/views/components/PrefixPlaceholder";
import {
	// Input, Select,
	Button,
	Col,
	Collapse,
	Form,
	Row,
	message,
	Tabs,
	Space,
	Drawer
} from "antd";
import AttrClassifyModal from "../ViewModal/AttrClassifyModal";
import { batchUpdateGoodsSpuInfo, getGoodsAttribute } from "../../../../service";
import Style from "./index.module.less";
import { useArchorList } from "./archorList";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import { DoubleLeftOutlined, ContainerTwoTone } from "@ant-design/icons";
import AttrList from "../ViewModal/AttrList";
import CommonDrawer from '@/components/CommonDrawer';
const ARCHOR_LIST_MAP = {
	basicInformation: 0, // 基础信息
	attributes: 1 // 商品属性
};

const SpuViewModal = props => {
	const { selectedKeys, onCancel, fetchList } = props;
	const [form] = Form.useForm();
	// 商品属性数据
	const [attrList, setAttrList] = useState([]);
	const [oldAttrList, setOldAttrList] = useState([]);
	// 弹窗相关
	const [dialogName, setDialogName] = useState("");
	const [visible, setVisible] = useState(false);

	// 锚点
	const archorList = useArchorList();
	const [tab, setTab] = useState(archorList[ARCHOR_LIST_MAP.basicInformation].key);
	const contentWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(contentWrapperRef, anchorItems);

	useEffect(() => {
		archorList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key);
		});
	}, []);

	function handleOk() {
		form.validateFields().then(val => {
			const API_DATA = form.getFieldsValue();
			API_DATA.attributes = attrList.map((item, index) => {
				return {
					...item,
					attributeId: item.id,
					attributeName: item.attributeName || null,
					attributeValue: API_DATA["attributes"][index].value ?? null
				};
			});

			console.log("API_DATA", API_DATA);
			batchUpdateGoodsSpuInfo({ ...API_DATA, ids: selectedKeys })
				.then(res => {
					const { msg, success } = res;
					if (success) {
						message.success(msg);
						onCancel();
						fetchList();
					}
				})
				.catch(err => {
					console.log("err", err);
				});
		});
	}

	// 获取分类属性列表
	const getAttrList = async pre => {
		const { data, success } = await getGoodsAttribute();
		if (success) {
			const attributesList = data.map((item, index) => {
				if (item.type === 1)
					item.options = item.attributeValue.split(",").map(val => {
						return {
							label: val,
							value: val
						};
					});
				return {
					...item,
					value: (pre && pre[index]?.value) || item.value
				};
			});
			setAttrList([...attributesList]);
			form.setFieldsValue({
				attributes: attributesList
			});
		}
	};
	useEffect(() => {
		getAttrList();
	}, []);

	useEffect(() => {
		// 打开分类属性需要把商品属性存起来
		if (dialogName === "AttrClassifyModal") {
			console.log("dialogName", dialogName);
			console.log(form.getFieldValue("attributes"));
			setOldAttrList(form.getFieldValue("attributes"));
		}
	}, [dialogName]);

	return (
		<CommonDrawer
			title="按款批量修改信息"
			open={true}
			width="80%"
			onOk={handleOk}
			onClose={onCancel}
			okText="保存"
			footer={
				<Row justify="space-between" style={{ alignItems: "center" }}>
					<Col className="common-color11">当前勾选生效{selectedKeys.length ?? 0}条商品</Col>
					<Col>
						<Space>
							<Button size="middle" onClick={onCancel}>
								取消
							</Button>
							<Button size="middle" type="primary" onClick={handleOk}>
								保存
							</Button>
						</Space>
					</Col>
				</Row>
			}
		>
			<div className={Style.archor_tab + " rule-reset"}>
				<Tabs
					activeKey={tab}
					onChange={val => {
						setTab(val);
						scrollToAnchor(val);
					}}
				>
					{archorList.map(item => (
						<Tabs.TabPane tab={item.title} key={item.key}></Tabs.TabPane>
					))}
				</Tabs>
			</div>
			<div className={Style.detail_inner} ref={contentWrapperRef}>
				<Form form={form}>
					<Collapse
						defaultActiveKey={Object.keys(ARCHOR_LIST_MAP)}
						ghost
						expandIcon={({ isActive }) => (
							<DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: "16px", color: "#4E5969" }} />
						)}
						expandIconPosition="end"
						className={Style["reset-collapse"]}
					>
						<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.basicInformation].render()} key="basicInformation">
							<Row gutter={[12, 6]} id="basic-data">
								<Col span={12}>
									<Form.Item name="spuName">
										<CommonField
											Component={Input}
											props={{
												placeholder: "商品名称",
												showCount: true,
												maxLength: 100
											}}
										/>
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item name="spuAbbreviation">
										<CommonField
											Component={Input}
											props={{
												placeholder: "商品简称",
												maxLength: 64
											}}
										/>
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item name="costPrice" rules={[{ required: true, message: "成本价" }]}>
										<CommonInputNumber min={0} placeholder="成本价" precision={2} controls={false} style={{ width: "100%" }} />
										{/* <CommonInput Component={Input} placeholder="请输入成本价" aria-required /> */}
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item name="weight">
										<CommonInputNumber
											min={0}
											placeholder="重量"
											addonAfter="kg"
											precision={2}
											controls={false}
											style={{ width: "100%" }}
										/>
										{/* <CommonInput Component={Input} placeholder="重量" suffix="kg" /> */}
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item name="retailPrice">
										<CommonInputNumber min={0} placeholder="零售价" precision={2} controls={false} />
										{/* <CommonInput Component={Input} placeholder="请输入零售价" /> */}
									</Form.Item>
								</Col>
							</Row>
						</Collapse.Panel>
						<Collapse.Panel
							header={archorList[ARCHOR_LIST_MAP.attributes].render()}
							key="attributes"
							style={{ position: "relative" }}
						>
							<Button
								type="text"
								onClick={() => setDialogName("AttrClassifyModal")}
								style={{ position: "absolute", right: 0, top: "12px" }}
							>
								<ContainerTwoTone style={{ marginRight: 5 }} />
								维护分类属性
							</Button>
							<Row gutter={[12, 6]}>
								<AttrList name="attributes" initialValue={attrList} />
								{/* <Form.List name="attributes">
									{(fields, { add, remove }, { errors }) => (
										<>
											{fields.map((field, index) => {
												const item = attrList[field.name];
												return (
													<Col key={field.key} span={6}>
														<Form.Item {...field} name={field.name}>
															<CommonField
																key={field.key}
																Component={item?.type == 1 ? Select : Input}
																props={{
																	placeholder: `请输入${item?.name ?? ""}`,
																	options: item?.options || []
																}}
															/>
														</Form.Item>
													</Col>
												);
											})}
										</>
									)}
								</Form.List> */}
							</Row>
						</Collapse.Panel>
					</Collapse>
				</Form>
			</div>

			{dialogName === "AttrClassifyModal" && (
				<AttrClassifyModal
					attrList={attrList}
					setVisible={setVisible}
					getAttrList={getAttrList}
					oldAttrList={oldAttrList}
					onCancel={() => {
						setDialogName("");
					}}
				/>
			)}
		</CommonDrawer>
	);
};
export default SpuViewModal;
